<template>
  <!-- 告警处理 -->
  <BaseMainSlot>
    <template v-slot:btnsBar>
      <!-- <SelectButton
        :buttonselectlist="selectbutlist"
        @nowselectbuttonindex="gettabletype"
      />-->
      <ActionBar />
    </template>
    <template v-slot:searchbox>
      <div class="seach-box">
        <div class="select-box-content">
          <div class="select-box-content-name">告警数据类型：</div>
          <el-select v-model="alarmTypeId" clearable @change="search()">
            <el-option
              v-for="(item,index) in alarmTypeList"
              :key="index"
              :label="item.alarmTypeName"
              :value="item.alarmTypeId"
            />
          </el-select>
        </div>
        <div class="select-box-content">
          <div class="select-box-content-name">数据类型：</div>
          <el-select v-model="dataTypeId" clearable @change="search()">
            <el-option
              v-for="(item,index) in dataTypeList"
              :key="index"
              :value="item.dataTypeId"
              :label="item.dataTypeName"
            />
          </el-select>
        </div>
        <div class="select-box-content">
          <div class="select-box-content-name">监测数据项：</div>
          <el-select v-model="dataItemId" clearable @change="search()">
            <el-option
              v-for="(item,index) in dataitemList"
              :key="index"
              :value="item.dataItemId"
              :label="item.originalName"
            />
          </el-select>
        </div>
        <div class="select-box-content">
          <div class="select-box-content-name">日期：</div>
          <el-date-picker
            v-model="seleteDate"
            type="datetimerange"
            :picker-options="pickerOptions"
            value-format="yyyy-MM-dd HH:mm:ss"
            format="yyyy-MM-dd HH:mm:ss"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            align="right"
            @change="queryPageList()"
          />
        </div>
        <div class="operationBtn">
          <div class="screenBtn">
            <div class="btn" @click="changeSelect()">
              <i
                :class="activeName === '' ? 'el-icon-d-arrow-right' : 'el-icon-d-arrow-left'"
                class="arrow-down"
              ></i>
            </div>
          </div>
        </div>

        <el-collapse v-model="activeName" accordion @change="handleChange">
          <el-collapse-item name="1">
            <div class="select-box-content">
              <div class="select-box-content-name">设备名称：</div>
              <div
                class="select-box-content-all"
                @click="cancelSelect('equipmentCode')"
              >全部</div>
              <div
                v-for="(item, index) in allEquipmentList"
                :key="index"
                class="select-box-content-list"
                :style="{ color: equipmentCode === item.equipmentCode ? '#54DEE2' : '#C1CFD2' ,fontWeight : equipmentCode === item.equipmentCode ? '600':'400' }"
                @click="selectEquipmentCode(item.equipmentCode)"
              >{{ item.equipmentName }}</div>
            </div>
            <div class="select-box-content">
              <div class="select-box-content-name">监测数据：</div>
              <div
                class="select-box-content-all"
                @click="cancelSelect('dataItemId')"
              >全部</div>
              <div
                v-for="(item, index) in dataitemList"
                :key="index"
                class="select-box-content-list"
                :style="{ color: dataItemId === item.dataItemId ? '#54DEE2' : '#C1CFD2' ,fontWeight : dataItemId === item.dataItemId ? '600':'400' }"
                @click="selectDataItemId(item.dataItemId)"
              >{{ item.dataItemName }}</div>
            </div>
          </el-collapse-item>
        </el-collapse>
      </div>
    </template>
    <template v-slot:content>
      <e-table
        ref="tableData"
        rowKey="baseAlarmId"
        :table-data="tableData"
        :table-columns="tableLabel"
        :page="currentPage"
        :size="pageSize"
        :total="totalSize"
        :loading="loading"
        :table-option="tableOption"
        @sizeChange="changePageSize"
        @pageChange="changeCurrentPage"
        @tableUpdatePlus="mixTableUpdatePlus"
        :showSelectColumn="false"
      >
        <template
          v-if="scoped.row.baseAlarmId"
          :style="{'color': scope.row.disposeStatus === true ? '#5cb87a' : '#f56c6c'} "
          slot-scope="scoped"
          slot="disposeStatus"
        >{{ filtername(scoped.row.disposeStatus) }}</template>
        <template
          slot="operate"
          v-if="scoped.row.baseAlarmId"
          slot-scope="scoped"
        >
          <span
            class="table-btns-box"
            @click="getalrmmessage(scoped.row)"
            v-if="scoped.row.alarmMessageId"
          >
            <i class="el-icon-view"></i>
            <span>查看详情</span>
          </span>
          <span
            class="table-btns-box"
            @click="handlingmmessage(scoped.row)"
            v-if="judgePermission(166,'handle')"
          >
            <i class="el-icon-s-claim"></i>
            <span>处理</span>
          </span>
        </template>
      </e-table>
    </template>
    <template v-slot:dialog>
      <el-dialog
        title="处理结果"
        label-position="left"
        :visible.sync="dialogVisible"
        @close="cancel"
      >
        <el-form ref="form" label-width="80px">
          <el-form-item label="处理结果:" class="w100p">
            <el-select
              v-model="defaulthandindex"
              width="100%"
              @change="defaulthandmet"
            >
              <el-option
                v-for="(deaitem, deaindex) in defaulthandinglist"
                :key="deaindex"
                :value="deaindex"
                :label="deaitem"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="处理意见:" class="w100p">
            <el-autocomplete
              type="textarea"
              style="width: 100%"
              v-model="formData.disposeContent"
              :fetch-suggestions="querySearch"
              placeholder="请输入处理意见"
              @select="handleSelect"
            ></el-autocomplete>
          </el-form-item>
          <el-form-item class="w100p red" label="温馨提示：你可以将处理意见设为模板，以便下次处理！">
            <!-- 设为模板 -->
            <el-button
              type="success"
              :disabled="!formData.disposeContent"
              @click="setTemplate"
              style="margin: 0 auto"
              plain
            >设为模板</el-button>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button class="zh-button-one" @click="cancel">取 消</el-button>
          <el-button
            class="zh-button-two"
            type="primary"
            @click="clickqueren"
          >确 定</el-button>
        </span>
      </el-dialog>
    </template>
  </BaseMainSlot>
</template>
<script>
import historicalAlarmRecord from "@/views/monitoring-alarmManagement/historical-alarm-record/index";

import ActionBar from "@/components/ActionBar";
import nowpagereqs from "@/api/monitoring-alarm/alarm-category-management";

import userreq from "@/api/user/index";
import nowpagereq from "@/api/monitoring-alarm/historical-alarm-record/index";
import BaseMainSlot from "@/components/BaseMainSlot/kong-new.vue";
import alarmNowpagereq from "@/api/monitoring-alarm/alarm-category-management/index";
import { mymixin } from "@/utils/mixin";

import { mapGetters } from "vuex";
export default {
  name: "AlarmHandling",
  components: {
    BaseMainSlot,
    ActionBar,
    historicalAlarmRecord,
  },
  mixins: [mymixin],
  data() {
    return {
      // 选中
      checkedIdList: [],
      // 可选择设备
      allEquipmentList: [],
      equipmentCode: "",
      // 查询条件
      alarmTypeList: [], //可选告警类型
      alarmTypeId: "",
      dataitemList: [], //可选数据项
      dataItemId: "",
      dataTypeList: [], //可选数据类型
      dataTypeId: "",
      seleteDate: [], //查询日期
      startTime: "",
      endTime: "",
      resultList: [
        { name: "已处理完成", id: "COMPLETED" },
        { name: "未处理", id: "UNCOMPLETED" },
        { name: "其他", id: "OTHER" },
      ],
      tableLabel: [
        {
          label: "告警名称",
          param: "baseAlarmName",
          show: true,
          notSearch: true,
        },
        {
          label: "告警设备名称",
          param: "batchName",
          show: true,
          notSearch: true,
        },
        {
          label: "告警数据项",
          param: "dataItemName",
          show: true,
          notSearch: true,
        },
        {
          label: "预设告警值",
          param: "alarmPresetValue",
          show: true,
          notSearch: true,
        },
        {
          label: "实际告警值",
          param: "actualAlarmValue",
          show: true,
          notSearch: true,
        },
        {
          label: "负责人",
          param: "alarmCharge",
          show: true,
          notSearch: true,
        },
        {
          label: "发生时间",
          param: "generateTime",
          type: "datetime",
          show: true,
          notSearch: true,
        },
        {
          label: "告警数据类型",
          param: "dataTypeName",
          notSearch: true,
          show: true,
        },
        {
          label: "告警信息状态",
          param: "disposeStatus",
          slotName: "disposeStatus",
          notSearch: true,
          show: true,
        },
        {
          label: "处理时间",
          param: "disposeTime",
          notSearch: true,
          show: true,
        },
        {
          label: "处理意见",
          param: "disposeContent",
          notSearch: true,
          show: true,
        },
      ],
      // 表单事件
      tableOption: {
        label: "操作",
        options: [
          {
            label: "操作",
            slotName: "operate",
          },
        ],
      },
      editLists: false, //用于判断是否是批量处理
      disposeList: [],
      disposeFlag: true,
      dispose: true,
      dialogVisiblethree: false,
      // 可选择数据类型
      dataTypeList: [],
      // 可选择批次
      batchList: [],
      // 前后一小时数据
      dialogVisibletwo: false,
      echartlist: {
        xAxisdata: [],
        xData: ["前后一小时数据"],
        seriesData: [],
      },
      nowwarringmessage: {},
      // -----------
      defaulthandinglist: ["已处理完成", "忽略", "其他"],
      defaulthandindex: 0,
      dialogVisible: false,
      nowselecttype: 0, // 0为物联自动告警 2为手动记录告警 1为数值告警
      dataitemlist: [],
      searchlist: {
        dataItemId: "",
        date: "",
      },
      // 选择类型
      selectbutlist: [{ name: "待处理" }, { name: "已处理" }],
      // 选中的数据项数组 employeeId组成 (此数组最多为一个)
      nowselectedList: [],
      // 可选择所有地块
      alarmTypeList: [],
      // 设施
      facilityList: [],
      facilityNo: "",
    };
  },
  computed: {
    ...mapGetters({
      judgePermission: "permission/judgePermission",
    }),
  },
  watch: {},
  created() {},
  mounted() {
    this.getselecltlist();
    this.queryPageList();
  },
  methods: {
    // 获取不同类型的表格数据
    gettabletype(i) {
      this.tableData = [];
      this.currentPage = 1;
      this.nowselecttype = i;
      if (i === 0) {
        this.tableColumn = this.tableColumn1;
      } else {
        this.tableColumn = this.tableColumn2;
      }
      this.queryPageList();
    },
    // 查询模板
    async queryTemplate(e) {
      this.templateType = e.dataTypeName;
      let params = {
        url: this.$route.path,
        organizationNo: sessionStorage.getItem("organizationNo"),
        type: e.dataTypeName,
      };
      let res = await alarmNowpagereq.queryTemplate(params);
      if (res.code === 1) {
        this.templateList = res.data;
        this.templateList.forEach((el) => {
          el.value = el.content;
        });
      }
    },
    querySearch(queryString, cd) {
      cd(this.templateList);
    },
    // TODO: 设为模板
    async setTemplate() {
      let params = {
        url: this.$route.path,
        account: sessionStorage.getItem("account"),
        organizationNo: sessionStorage.getItem("organizationNo"),
        type: this.templateType,
        content: this.formData.disposeContent,
      };
      let res = await alarmNowpagereq.setTemplate(params);
      if (res.code === 1) {
        this.$message.success("设置模板成功！");
      } else if (res.msg === "该处理意见已存在！") {
        this.$message.error("该模板已存在！");
      } else {
        this.$message.error("设置模板失败！");
      }
    },
    // 排序模板
    async handleSelect(e) {
      await alarmNowpagereq.sortTemplate(e.processContentId);
    },
    querySearch(queryString, cd) {
      cd(this.templateList);
    },
    changeTableSort(column) {
      this.sortList = column.order
        ? [
            {
              property: column.prop,
              direction: column.order == "ascending" ? "asc" : "desc",
            },
          ]
        : [];
      this.queryPageList();
    },
    // 表格中的标签
    filterTag(value, row) {
      return row.disposeStatus === value;
    },
    // 表格中的标签
    filtername(value) {
      if (value) {
        return "已处理";
      } else {
        return "待处理";
      }
    },
    // 处理
    async handlingmmessage(e) {
      // TODO: 查询模板
      await this.queryTemplate(e);
      this.formData = {};
      this.dialogVisible = true;
      if (this.nowselecttype === 1) {
        if (e.numericalAlarmMessageId) {
          this.formData.numericalAlarmMessageId = e.numericalAlarmMessageId;
        }
      }
      if (this.nowselecttype === 0) {
        if (e.alarmMessageId) {
          this.formData.alarmMessageId = e.alarmMessageId;
        }
      }
    },
    // 默认处理意见
    defaulthandmet(i) {
      if (i === 0) {
        this.formData.disposeStatus = true;
      } else if (i === 1) {
        this.formData.disposeStatus = false;
      } else if (i === 3) {
        this.formData.disposeStatus = true;
      }
    },
    // 点击弹框确认-批量处理
    // 点击弹框确认
    async clickqueren() {
      this.dialogVisible = false;
      this.formData.disposeTime = this.dateToFormat(new Date());
      if (this.defaulthandindex == 0) {
        this.formData.disposeStatus = true;
      } else {
        this.formData.disposeStatus = true;
      }
      if (!this.formData.disposeContent) {
        this.formData.disposeContent = "";
      }
      console.log(this.formData, this.editLists);
      // TODO:批量处理
      if (this.editLists) {
        let params = [];
        this.disposeList.map((el) => {
          params.push({
            alarmMessageId: el.alarmMessageId,
            disposeStatus: this.formData.disposeStatus,
            disposeContent: this.formData.disposeContent,
            disposeTime: this.dateToFormat(new Date()),
          });
        });
        console.log(params, "批量处理");
        let res = await nowpagereq.editlists(params);
        if (res.code === 1) {
          this.queryPageList();
          this.$message.success("批量处理成功");
          this.resetTable();
        } else {
          this.$message.error("批量处理失败");
        }
        return;
      } else {
        //单个处理
        console.log("单个处理");
        nowpagereq.editlist(this.formData).then((res) => {
          if (res.code === 1) {
            this.queryPageList();
            this.$message.success("处理成功");
          } else {
            this.$message.error("处理失败");
          }
        });
      }
    },
    // 查看详细数据
    getalrmmessage(e) {
      this.$alert(e.message, "详细数据", {
        showConfirmButton: false,
        closeOnClickModal: true,
        confirmButtonClass: "zh-button-two",
      }).catch((_) => {});
    },
    // 获取前一小时数据
    getbeforertime(originDate) {
      const dt = new Date(originDate);
      const y = dt.getFullYear();
      const m = (dt.getMonth() + 1 + "").padStart(2, "0");
      const d = (dt.getDate() + "").padStart(2, "0");
      const hh = (dt.getHours() - 1 + "").padStart(2, "0");
      const mm = (dt.getMinutes() + "").padStart(2, "0");
      const ss = (dt.getSeconds() + "").padStart(2, "0");
      return `${y}-${m}-${d} ${hh}:${mm}:${ss}`;
    },
    // 获取后一小时数据
    getaftertime(originDate) {
      const dt = new Date(originDate);
      const y = dt.getFullYear();
      const m = (dt.getMonth() + 1 + "").padStart(2, "0");
      const d = (dt.getDate() + "").padStart(2, "0");
      const hh = (dt.getHours() + 1 + "").padStart(2, "0");
      const mm = (dt.getMinutes() + "").padStart(2, "0");
      const ss = (dt.getSeconds() + "").padStart(2, "0");
      return `${y}-${m}-${d} ${hh}:${mm}:${ss}`;
    },
    // 布尔值格式化
    formatBoolean(row, column, cellValue) {
      var ret = ""; // 你想在页面展示的值
      if (cellValue) {
        ret = "已处理"; // 根据自己的需求设定
      } else if (cellValue === false) {
        ret = "待处理";
      }
      return ret;
    },
    // 获取下拉选择数据
    getselecltlist() {
      // 获取所有监测数据项
      nowpagereq.getdataitemlist().then((res) => {
        this.dataitemlist = res.data;
      });
      let params = {
        organizationList: sessionStorage
          .getItem("organizationList")
          .split(",")
          .concat([sessionStorage.parentId || ""]),
        farmingTypeNo: sessionStorage.getItem("farmingTypeNo"),
      };
      // 获取设施
      userreq.getfacilityAll(params).then((res) => {
        this.facilityList = res.data;
      });
      // 获取批次
      let batchListParams = {
        simpleData: true,
      };
      nowpagereq.getbatchlist(batchListParams).then((res) => {
        this.batchList = res.data;
      });
      alarmNowpagereq.getalldatalist().then((res) => {
        this.dataTypeList = res.data;
      });
      let faciparams = {
        organizationList: sessionStorage
          .getItem("organizationList")
          .split(",")
          .concat([sessionStorage.parentId || ""]),
        farmingTypeNo: sessionStorage.getItem("farmingTypeNo"),
      };
      nowpagereqs.querybycondition(faciparams).then((res) => {
        this.alarmTypeList = res.data;
      });
    },
    queryPageListtwo() {
      this.loading = true;
      let searchparam = {};
      if (this.searchlist.date && this.searchlist.date[0]) {
        searchparam.startTime = this.dateToFormat(this.searchlist.date[0]);
      }
      if (this.searchlist.date && this.searchlist.date[1]) {
        searchparam.endTime = this.dateToFormat(this.searchlist.date[1]);
      }
      searchparam.category = this.searchlist.category || undefined;
      searchparam.batchNo = this.searchlist.batchNo || undefined;
      searchparam.dataTypeId = this.searchlist.dataTypeId || undefined;
      searchparam.dataItemId = this.searchlist.dataItemId || undefined;
      searchparam.alarmTypeId = this.searchlist.alarmTypeId || undefined;
      searchparam.facilityNo = this.searchlist.facilityNo || undefined;
      let params = {
        page: this.currentPage,
        size: this.pageSize,
        entity: {
          ...searchparam,
          simpleEntity: false,
        },
        sortList: this.sortList || [],
      };
      this.entity = params.entity;
      nowpagereq.getlist(params).then((res) => {
        this.loading = false;
        if (res.code === 0) {
          this.$message.error("当前告警历史表格获取失败");
        }
        let data = res.data.content;
        // 赋值总条数
        this.totalSize = res.data.totalElements;
        // 赋值数组
        this.tableData = data;
        this.addblankmet();
        this.resetActionBar();
      });
    },
    search(e) {
      this.queryPageList(e);
    },
    // 获取当前拥有类型表格
    queryPageList(e) {
      this.loading = true;
      let entity = {
        result: "UNCOMPLETED",
      };
      if (this.seleteDate) {
        entity.startTime = this.seleteDate[0];
        entity.endTime = this.seleteDate[1];
      }
      if (this.dataTypeId) {
        entity.dataTypeId = this.dataTypeId;
      }
      if (this.dataItemId) {
        entity.dataItemId = this.dataItemId;
      }
      if (this.alarmTypeId) {
        entity.alarmTypeId = this.alarmTypeId;
      }
      if (this.equipmentCode) {
        entity.batchNo = this.equipmentCode;
      }
      if (e) {
        entity = { ...e };
      }
      let params = {
        page: this.currentPage,
        size: this.pageSize,
        entity: entity,
      };
      nowpagereq.getlist(params, false).then((res) => {
        this.loading = false;
        if (res.code === 0) {
          this.$message.error("当前告警历史表格获取失败");
        }
        let data = res.data.content;
        // 赋值总条数
        this.totalSize = res.data.totalElements;
        // 赋值数组
        this.tableData = data;
        this.addblankmet();
        this.resetActionBar();
      });
    },
    search() {
      this.currentPage = 1;
      this.queryPageList();
    },
    // TODO:批量处理
    disposed() {
      this.dialogVisible = true;
    },
    handleSelectionChange(list) {
      if (list.length > 0) {
        this.editLists = true;
        this.disposeFlag = false;
        this.disposeList = list;
        console.log(list, "list");
        //业务处理
      } else {
        this.disposeFlag = true;
        this.editLists = false;
      }
      console.log(this.editLists, "pi");
    },
    // 重置表格
    resetTable() {
      this.$refs.tableData.clearSelection();
      this.formData.disposeContent = "";
    },
    cancel() {
      this.dialogVisible = false;
      this.templateContent = "";
      this.formData.disposeContent = "";
      this.resetTable();
    },

    async download() {
      let params = {
        entity: {
          ...this.entity,
          organizationNo: sessionStorage.getItem("organizationNo"),
          farmingTypeNo: sessionStorage.getItem("farmingTypeNo"),
          system: "SC",
          disposeStatus: true,
        },
      };
      let url = "v3/alarm/alarmMessage/download";
      let excel = "历史告警记录表";
      this.downloadExcel(url, params, excel);
    },
  },
};
</script>
<style lang="scss" scoped>
::v-deep .el-collapse-item__header {
  height: 0px;
}
::v-deep .el-collapse-item__content {
  padding-bottom: 10px;
}
.table-spec {
  margin-top: 10px;
}
</style>
